﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.NET.Core.Service;
using Admin.NET.Core;
using Admin.Net.InformationPlatform.Entity.Maintenance;
using Admin.Net.InformationPlatform.Entity;
using Admin.Net.InformationPlatform.Service.Maintenance.Dto;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.Net.InformationPlatform.Entity.ProdectFile;
using Admin.Net.InformationPlatform.Service.ProjectFile.Dto;

namespace Admin.Net.InformationPlatform.Service.ProjectFile
{

    /// <summary>
    /// 华为验厂-SOP文件管理
    /// </summary>
    [ApiDescriptionSettings(groups: "HWYC", Name = "SOP文件管理", Tag = "SOP文件管理", Order = 200)]

    public class ProjectFileService : IDynamicApiController, ITransient
    {
        /// <summary>
        /// 单例数据链接
        /// </summary>
        ISqlSugarClient db;
        /// <summary>
        /// T100数据库
        /// </summary>
        private SqlSugarProvider _T100Db;
        private SqlSugarProvider _SjDb;
        private SqlSugarProvider _plm;
        private SqlSugarProvider _Dilon;


        /// <summary>
        /// 用户信息
        /// </summary>
        TokenUser _User;
        /// <summary>
        /// SOP工程文件管理
        /// </summary>
        /// <param name="db"></param>
        public ProjectFileService(ISqlSugarClient db)
        {
            this.db = db;
            this._T100Db = this.db.AsTenant().GetConnection(T100TestArea.ConfigId);
            this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
            this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
            this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
            // 获取 `Jwt` 存储的信息 企业编号与据点信息
            _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

        }
        /// <summary>
        ///  获取品名对应的工程文件列表-分页
        /// </summary>
        /// <returns></returns>
        [HttpPost("/HWYC/GetProjectFilePagedList")]
        public async Task<SqlSugarPagedList<HW_PRODECT_FILE>> GetMouldPagedList(ProjectFileInput input)
        {

            var output = await _SjDb.Queryable<HW_PRODECT_FILE>()
.Where(l => l.ISDELETE == 0)
.WhereIF(!string.IsNullOrEmpty(input.PRODECTNAME), (l) => (l.PRODECTNAME.Contains(input.PRODECTNAME)))//品名

.OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建日期排序
.Select(l => new HW_PRODECT_FILE
{
    ID = l.ID,
    PRODECTNAME = l.PRODECTNAME,
    FILEPATH = l.FILEPATH,
    CREATETIME =l.CREATETIME,
    FILENAEM = l.FILENAEM,
    USERID =l.USERID,
    USERNAME =l.USERNAME,
    BBH = l.BBH


}).ToPagedListAsync(input.Page, input.PageSize);
            return output;
        }


        /// <summary>
        ///  获取品名对应的工程文件列表-分页（历史记录）
        /// </summary>
        /// <returns></returns>
        [HttpPost("/HWYC/GetProjectFileHisPagedList")]
        public async Task<SqlSugarPagedList<HW_PRODECT_FILE>> GetProjectFileHisPagedList(ProjectFileInput input)
        {
            var output = await _SjDb.Queryable<HW_PRODECT_FILE>()
.Where(l => l.ISDELETE == 1)
.WhereIF(!string.IsNullOrEmpty(input.PRODECTNAME), (l) => (l.PRODECTNAME==input.PRODECTNAME))//品名
.OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建日期排序
.Select(l => new HW_PRODECT_FILE
{
    ID = l.ID,
    PRODECTNAME = l.PRODECTNAME,
    FILEPATH = l.FILEPATH,
    CREATETIME = l.CREATETIME,
    FILENAEM = l.FILENAEM,
    USERID = l.USERID,
    USERNAME = l.USERNAME,
    BBH = l.BBH


}).ToPagedListAsync(input.Page, input.PageSize);
            return output;
        }
        /// <summary>
        /// 增加SOP工程文件
        /// </summary>
        /// <returns></returns>
        [HttpPost("/HWYC/AddProjectFile")]
        public async Task<string> AddQuestion(HW_PRODECT_FILE[] input)
        {
            List<HW_PRODECT_FILE> list = new List<HW_PRODECT_FILE>();
            if (input.Count() > 0)
            {
                for(int i = 0; i < input.Count(); i++)
                {
                    //判断单据存在
                    int cnt = await _SjDb.Queryable<HW_PRODECT_FILE>()
                        .Where(a => a.PRODECTNAME == input[i].PRODECTNAME)
                        .Select(a => a.ID)
                        .CountAsync();
                    if (cnt != 0)//有数据时，先进行伪删除再添加
                    {
                        _SjDb.Ado.BeginTran();
                        int count = await _SjDb.Updateable<HW_PRODECT_FILE>()
                            .SetColumns(a => a.ISDELETE == 1)
                            .Where(a => a.PRODECTNAME == input[i].PRODECTNAME && a.ISDELETE == 0)
                            .ExecuteCommandAsync();
                    }
                    var details = new HW_PRODECT_FILE
                    {
                        ID = Guid.NewGuid().ToString("N"),
                        PRODECTNAME = input[i].PRODECTNAME,
                        FILEPATH = input[i].FILEPATH,
                        ISDELETE = 0,
                        CREATETIME = DateTime.Now,
                        FILENAEM = input[i].FILENAEM,
                        USERID = _User.UserId,
                        USERNAME = _User.RealName,
                        BBH = "V" + (cnt + 1).ToString(),
                    };
                    list.Add(details);

                }
            }
            #region 插入事务
            try
            {
                //开启事务
                _SjDb.Ado.BeginTran();
                int cnt = await _SjDb.Insertable<HW_PRODECT_FILE>(list).ExecuteCommandAsync();

                if (cnt == 0)
                {
                    throw Oops.Oh($"新建任务失败！");
                }
                //提交事务
                _SjDb.Ado.CommitTran();
                return "插入成功";
            }
            catch (Exception e)
            {
                //回滚事务
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }
            #endregion

        }
       
        /// <summary>
        /// SOP工程文件删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/HWYC/DeleteProductName")]
        public async Task<string> DeleteProductName(ProjectFileDelete input)
        {
            //判断单据存在
            int cnt = await _SjDb.Queryable<HW_PRODECT_FILE>()
                .Where(a => a.ID == input.ID)
                .Select(a => a.ID)
                .CountAsync();
            if (cnt == 0)
            {
                throw Oops.Oh("任务不存在，驳回！");
            }
            else
            {
                //提交
                try
                {
                    _SjDb.Ado.BeginTran();
                    int count = await _SjDb.Updateable<HW_PRODECT_FILE>()
                        .SetColumns(a => a.ISDELETE == 1)
                        .Where(a => a.ID == input.ID)
                        .ExecuteCommandAsync();

                    if (count != 1)
                    {
                        throw Oops.Oh("删除失败！");
                    }
                    _SjDb.Ado.CommitTran();
                    return "删除成功！";
                }
                catch (Exception e)
                {
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }
            }
        }
        /// <summary>
        /// 获取品名下拉框列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("/SRM/GetPMList")]
        public async Task<object> GetPMPHList(GetPMList input)
        {
            return _T100Db.Ado.SqlQuery<PmPhList>($@"
                    select 
distinct imaal003 value
from dsdata.imaal_t  l
left join dsdata.imaa_t a on l.imaal001 = a.imaa001 and l.imaalent = a.imaaent
where IMAA010='03' and IMAASTUS='Y' and 
IMAAENT='8' and imaal003 like '%{input.ProductNAME}%'
                    ").ToJson();
        }
    }
}
